from flask import Flask, jsonify
from apscheduler.schedulers.background import BackgroundScheduler
from datetime import datetime, timedelta
import requests
import fitz  # PyMuPDF
import pytz
import os
import time
from llm_model import llm_extract_resume
from util import TokenAccess,GetApplicantList,ResumeExtraction,ConstructPrompt,UpdateField
def process_resumes():
    global token,url,startTime,endTime

    endTime = datetime.now(beijing_tz)

    start_time = startTime.strftime('%Y-%m-%dT%H:%M:%S')
    end_time = endTime.strftime('%Y-%m-%dT%H:%M:%S')
    print("程序开始运行",end_time)
    time1 = time.time()
    if token is None:
        token = TokenAccess(url)

    data = GetApplicantList(url, start_time, end_time, token)
    if data is None or 'items' not in data:
        print("没有获取到申请人数据")
    else:
        applicants = data['items']
        for applicant in applicants:
            prompt, text = ConstructPrompt(url, token, applicant)
            try:
                response_json = llm_extract_resume("wenxin", prompt, text)
            except Exception as e:
                response_json = None
                print("调用大模型失败", e)

            if response_json:
                score = response_json['总评分']
                reason = response_json['总评分理由']
                risk = response_json['潜在风险']
                UpdateField(url, token, applicant, score, reason, risk)
                name = applicant['applicantLite']['name']
                print(name, "简历评分完成")
    time2 = time.time()
    elapsed_time = time2 - time1
    print("本次耗时：", elapsed_time)
    startTime = endTime-timedelta(seconds=5)
    print("预计下一轮抓取简历时间：", (endTime+timedelta(minutes=1)).strftime('%Y-%m-%dT%H:%M:%S'))

app = Flask(__name__)

# API 端点
url = 'https://openapi.italent.cn'
token = None
beijing_tz = pytz.timezone('Asia/Shanghai')
endTime = datetime.now(beijing_tz)
startTime = endTime - timedelta(minutes=1)

process_resumes()

@app.route('/start', methods=['GET'])
def start():
    process_resumes()
    return jsonify({"message": "简历处理已启动"})


if __name__ == '__main__':
    scheduler = BackgroundScheduler()
    scheduler.add_job(func=process_resumes, trigger="interval", minutes=1)
    scheduler.start()

    try:
        app.run(host='0.0.0.0', port=5000)
    except (KeyboardInterrupt, SystemExit):
        scheduler.shutdown()
